import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Input,
  Modal,
  message,
  Badge,
  Divider,
  Radio,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../search.less';
const FormItem = Form.Item;
const statusMap = ['error',  'success'];
const status = ['否',  '是'];

const UpdateForm = Form.create()(props => {
  const { updateModalVisible, form, handleUpdate, handleUpdateModalVisible, text } = props;
  const formItemLayout = {
    labelCol: {
      sm: { span: 4 },
    },
    wrapperCol: {
      sm: { span: 18 },
    },
  };
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleUpdate(fieldsValue,text.id);
    });
  };
  return (
    <Modal
      destroyOnClose
      width={640}
      title="编辑菜单"
      visible={updateModalVisible}
      onOk={okHandle}
      onCancel={() => handleUpdateModalVisible()}
      maskClosable={false}
    >
      <FormItem {...formItemLayout} label="菜单名称">
        {form.getFieldDecorator('name', {
          rules: [{required: true,whitespace:true, message:'名称不能为空'},{max:20,message:'名称不能超过20个字符'},],
          initialValue: text&&text.name||''
        })(<Input placeholder="请输入" />)}
      </FormItem>
      <FormItem {...formItemLayout} label="URL">
        {form.getFieldDecorator('path', {
          rules: [{ required: true, whitespace:true, message: 'URL不能为空'},{max: 64, message: 'URL不能超过64个字符'}],
          initialValue: text&&text.path||''
        })(<Input placeholder="请输入" />)}
      </FormItem>
        <FormItem {...formItemLayout} label="是否可见">
              {form.getFieldDecorator('isShow',{initialValue: text&&text.isShow||0,
              })(
                <Radio.Group>
                  <Radio value={0}>
                    否
                  </Radio>
                  <Radio value={1}>
                    是
                  </Radio>
                </Radio.Group>
              )}
            </FormItem>
    </Modal>
  );
});
/* eslint react/no-multi-comp:0 */
@connect(({ sysMenu, loading }) => ({
  sysMenu,
  loading: loading.models.sysMenu,
}))


@Form.create()
class sysMenu extends PureComponent {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    text: {},
  };

  columns = [
    {
      title: '菜单名称',
      dataIndex: 'name',
    },
    {
      title: 'URL',
      dataIndex: 'path',
    },
    {
      title: '是否可见',
      dataIndex: 'isShow',
      width: '10%',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    // {
    //   title: '序号',
    //   dataIndex: 'orderNum',
    //   defaultSortOrder: 'descend',
    //   sorter: (a, b) => b.orderNum - a.orderNum,
    // },

    {
      title: '操作',
      render: (text, record,index) => (
        <Fragment>
          <a onClick={() => this.handleUpdateModalVisible(true,text)}>编辑</a>

          {text.moveFlag=='undo'?null:<Divider type="vertical" />}

          {!text.moveFlag?<Fragment><a onClick={() => this.move(true,text.id)}>上移</a>
          <Divider type="vertical" />
          <a onClick={() => this.move(false,text.id)}>下移</a></Fragment>:null}

          {text.moveFlag=='first'?<a onClick={() => this.move(false,text.id)}>下移</a>:null}

          {text.moveFlag=='last'?<a onClick={() => this.move(true,text.id)}>上移</a>:null}

        </Fragment>
      )
    },
  ];

  componentDidMount() {
    this.queryList();
  }

  queryList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysMenu/queryList',
    });
  }

  move = (flag,id) => {
    const { dispatch } = this.props;
    const url = flag?'sysMenu/up':'sysMenu/down';
    const mean = flag?'上移':'下移';
    dispatch({
          type: url,
          payload: { id },
          callback: (res) => {
            if(res.result == "ok") {
              Modal.success({title: res.msg});
              this.queryList();
            }else {
              Modal.error({title: '操作失败',content: res.msg,});
            }
          },
        });
  };

  handleUpdateModalVisible = (flag,text) => {
    this.setState({
      updateModalVisible: !!flag,
      text,
    });
  };

  handleUpdate = (fields,id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysMenu/update',
      payload: {
        id,
        menuName: fields.name,
        menuUrl: fields.path,
        isShow: fields.isShow,
      },
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          this.queryList();
        }else {
          Modal.error({title: '操作失败',content: res.msg,});
        }
      },
    });
    this.handleUpdateModalVisible();
  };

  render() {
    const {
      sysMenu: { data },
      loading,
    } = this.props;
    const { selectedRows, updateModalVisible,text} = this.state;
    const updateMethods = {
      handleUpdate: this.handleUpdate,
      handleUpdateModalVisible: this.handleUpdateModalVisible,
    };

    return (
      <PageHeaderWrapper title="菜单管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              hideRowSelection={true}
              loading={loading}
              data={data}
              columns={this.columns}
              pagination={false}
              rowKey={record => record.id}
            />
          </div>
        </Card>
        <UpdateForm {...updateMethods} updateModalVisible={updateModalVisible} text={text} />
      </PageHeaderWrapper>
    );
  }
}

export default sysMenu;
